<template>
  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

    
    <!-- 课程信息表单 -->
    <el-form label-width="120px">
      <el-form-item label="课程标题" label-width="120px">
        <el-input v-model="courseInfo.title" placeholder="请输入课程标题"/>
      </el-form-item>

        <!-- 所属分类 -->
          <!-- 一级分类 -->
          <el-form-item label="课程分类">
            <el-select
                v-model="courseInfo.subjectParentId"
                placeholder="一级分类" @change="subjectLevelOneChanged">

                <el-option
                    v-for="subject in subjectOneList"
                    :key="subject.id"
                    :label="subject.title"
                    :value="subject.id"/>

            </el-select>

            <!-- 二级分类 -->
            <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
                <el-option
                    v-for="subject in subjectTwoList"
                    :key="subject.value"
                    :label="subject.title"
                    :value="subject.id"/>
            </el-select>
        </el-form-item>


        <!-- 课程讲师 -->
        <el-form-item label="课程讲师">
          <el-select
            v-model="courseInfo.teacherId"
            placeholder="请选择">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"/>
          </el-select>
        </el-form-item>


        <el-form-item label="总课时">
          <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
        </el-form-item>

        <el-form-item label="课程价格">
          <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
        </el-form-item>

        <!-- 课程封面 -->
        <el-form-item label="课程封面">
          <el-upload
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="BASE_API+'/eduoss/fileoss'"
                class="avatar-uploader">
              <img width="150px" height="150px" :src="courseInfo.cover" class="avatar">
            </el-upload>
        </el-form-item>


        <!-- 课程简介 -->
        <el-form-item label="课程简介">
            <tinymce :height="300" v-model="courseInfo.description"/>
        </el-form-item>
          
        <el-form-item>
          <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
        </el-form-item>
        
    </el-form>
  </div>
</template>
<script>
import courseApi from '@/api/edu/courserApi'
import subject from '@/api/edu/subject'
import teacher from '@/api/edu/teacher'
import Tinymce from '@/components/Tinymce'
export default {
  components:{Tinymce}, //声明富文本编辑器
  data() {
    return {
      courseInfo:{
        title: '',
        subjectId: '', //二级分类id
        subjectParentId:'', //一级分类id
        teacherId: '', //讲师id
        lessonNum: 0,
        description: '',
        cover: '/static/1.jpg', //默认封面
        price: 0
      },
      courseId:'',
      subjectOneList: [],//一级分类列表
      subjectTwoList: [],//二级分类列表
      teacherList:[], //讲师列表
      saveBtnDisabled: false, // 保存按钮是否禁用
      BASE_API: process.env.BASE_API // 接口API地址
    }
  },

  watch:{
    // 监听路由是否改变
    $route(to,from){
      this.init()
      
    }
  },

  created() {

    // 路由改变
    if(this.$route.params && this.$route.params.id){
      console.log(this.$route.params)
      console.log(this.$route.params.id)
      this.courseId = this.$route.params.id
      this.getCourseInfo()
    }
    this.initSubjectOneList() //获取一级分类
    this.initTeacherList() //获取讲师列表
    
  },

  methods: {
    // 修改bug，重新点击发布课程时，之前的数据没有清空
    init(){
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.getCourseInfo()
      }else{
         // 清空courseInfo中的数据。但是保留默认的
        this.courseInfo = {}
        this.courseInfo.cover = '/static/1.jpg'
        this.courseInfo.lessonNum = 0
        this.courseInfo.price = 0
      }
     
    },

  // 重新点击发布课程时清空课程信息
  getCourseInfoNull(id){
    courseApi.getCourseInfoById(id).then(res => {
      this.courseInfo = res.data.courseInfoVo
    })
  },


    // 根据id回显课程信息
    getCourseInfo(){
      courseApi.getCourseInfoById(this.courseId).then(res => {
        this.courseInfo = res.data.courseInfoVo
        // 解决二级分类回显问题
        subject.getTreeSubject().then(res => {
          // 得到所有的一级分类
          this.subjectOneList = res.data.list
          // 遍历一级分类
          for(let i = 0;i < this.subjectOneList.length; i++){
            // 判断一级分类下面的id是否与课程管理的一级分类id相同
            if(this.subjectOneList[i].id === this.courseInfo.subjectParentId){
              // 如果相同，遍历该一级分类下面的二级分类。
              this.subjectTwoList = this.subjectOneList[i].children
            }
          }
        })
        this.initSubjectOneList() //获取一级分类
        this.initTeacherList() //获取讲师列表
      })
    },

    // 上传封面成功调用的方法
    handleAvatarSuccess(res,file){
      this.courseInfo.cover = res.data.url
    },

    // 上传封面之前调用的方法
    beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
    },

    // 获取讲师列表
    initTeacherList() {
      teacher.getList().then(res => {
        this.teacherList = res.data.items
      })
    },

    // 初始化一级课程分类
    initSubjectOneList() {
      subject.getTreeSubject().then(res => {
        this.subjectOneList = res.data.list
      })
    },

    // 一级分类与二级分类联动
    subjectLevelOneChanged(value){
      for(let i = 0;i< this.subjectOneList.length;i++){ //遍历一级分类的所有选项
        //每个一级分类
        var oneSubject = this.subjectOneList[i]
        // 如果一级分类的id与value（选择一级分类的id，因为显示的是名称，带过来的是id）相同
        if(value === oneSubject.id){
          this.subjectTwoList = oneSubject.children
          this.courseInfo.subjectId = '' //如果重新选择了一级分类，把二级分类清空
        }
      }
    },


    // 保存并下一步
    saveOrUpdate() {
      // this.saveBtnDisabled = true //是否禁用保存
      // 如果路由中没有id，说明是保存
      if(!this.courseInfo.id){
        this.saveCourse()
      }else{
        this.updateCourse()
      }
    },
    
    // 保存
    saveCourse(){
      // 判断数据是否为空
      if(this.courseInfo.title === ''
        || this.courseInfo.teacherId === ''
        || this.courseInfo.subjectParentId === ''
        || this.courseInfo.subjectId === ''){
       
        this.$message({
          type: 'error',
          message: "请完整填写信息",
          
        })
        return false
      }

      courseApi.saveCourseInfo(this.courseInfo).then(res => {
          this.$message({
            type: 'success',
            message: '添加课程成功!'
          })
           return res// 将响应结果传递给then
      }).then(res => {
        this.$router.push({ path: '/course/chapter/' + res.data.courseId })
      }).catch((res) => {
        this.$message({
          type: 'error',
          message: "保存失败"
        })
      })
    },
    // 修改
    updateCourse(){
      // 判断是否为空对象
      if(this.courseInfo.title === ''
        || this.courseInfo.teacherId === ''
        || this.courseInfo.subjectParentId === ''
        || this.courseInfo.subjectId === ''){
       
        this.$message({
          type: 'error',
          message: "请完整填写信息",
          
        })
        return false
      }
      courseApi.updateCourseInfo(this.courseInfo).then(res => {
        this.$message({
            type: 'success',
            message: '修改课程成功!'
          });
           this.$router.push({ path: '/course/chapter/'+this.courseId })
      })
    }

  }
}
</script>
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>